document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('text-form');
    const statusDiv = document.getElementById('status');
    const unfinishedDiv = document.getElementById('unfinished-sentence');
    const detailedInfoDiv = document.getElementById('detailed-info');
    const progressBar = document.getElementById('progress-bar');
    const submitBtn = document.getElementById('submit-btn');
    const clearBtn = document.getElementById('clear-btn');
    const stopBtn = document.getElementById('stop-btn');
    const mergeBtn = document.getElementById('merge-btn'); // “马上合并”按钮
    const mergeFeedbackDiv = document.getElementById('merge-feedback'); // 用于显示合并反馈信息
    const fixGapsBtn = document.getElementById('fix-gaps-btn'); // “修复断层”按钮
    const fixProgressDiv = document.getElementById('fix-progress'); // 用于显示修复进度的div
    const filenameInput = document.getElementById('filename'); // 文件名输入框
    const speakerDropdown = document.getElementById('speaker-dropdown'); // 讲述人下拉菜单
    const clearFilenameBtn = document.getElementById('clear-filename-btn'); // 新增的“清空”按钮
    const editSpeakerBtn = document.getElementById('edit-speaker-btn'); // “编辑”按钮
    const editSpeakerModal = document.getElementById('edit-speaker-modal'); // 浮窗
    const closeBtn = document.querySelector('.close'); // 关闭浮窗按钮
    const addSpeakerBtn = document.getElementById('add-speaker-btn'); // 添加讲述人按钮
    const newSpeakerNameInput = document.getElementById('new-speaker-name'); // 新讲述人输入框
    const refreshBtn = document.getElementById('refresh-btn'); // 修复刷新按钮
    const advancedSettingsBtn = document.getElementById('advanced-settings-btn');
    const advancedSettingsModal = document.getElementById('advanced-settings-modal'); 
    const closeSettingsBtn = document.getElementById('close-settings-btn'); 
    const restoreDefaultsBtn = document.getElementById('restore-defaults-btn'); 
    const customSettingsInput = document.getElementById('custom-settings-input');
	const updateSettingBtn = document.getElementById('update-setting-btn');
    const mergeStatusDiv = document.getElementById('merge-status');
    // 帮助弹窗
    const helpBtn = document.getElementById('help-btn');
    const helpModal = document.getElementById('help-modal');
    const helpText = document.getElementById('help-text'); // 获取帮助内容的显示区域
    const closeHelpBtn = document.querySelector('.close-help');
	let logIntervalId = null;
	
		if (refreshBtn) {
        refreshBtn.addEventListener('click', () => {
            location.reload(); // 刷新页面
        });
    }
	    // 显示浮窗
    editSpeakerBtn.addEventListener('click', () => {
        editSpeakerModal.style.display = 'block';
    });

    // 关闭浮窗
    closeBtn.addEventListener('click', () => {
        editSpeakerModal.style.display = 'none';
    });
	
    // 定义一个函数，用于获取合并状态
    function fetchMergeStatus() {
        fetch('/merge_status')  // 发送请求到新的 API 路由
            .then(response => response.json())
            .then(data => {
                // 解析并显示合并状态
                if (data.is_processing) {
                    mergeStatusDiv.innerHTML = `
                        <p>当前策略: ${data.strategy}</p>
                        <p>当前文件: ${data.current_file}</p>
                        <p>进度: ${data.current_progress.toFixed(2)}%</p>
                        <p>已完成文件数: ${data.completed_files}/${data.total_files}</p>
                    `;
                } else if (data.error) {
                    mergeStatusDiv.innerHTML = `<p>错误: ${data.error}</p>`;
                } else {
                    mergeStatusDiv.innerHTML = `<p>合并完成!</p>`;
                }
            })
            .catch(error => {
                console.error('Error fetching merge status:', error);
                mergeStatusDiv.innerHTML = `<p>无法获取合并状态，请稍后再试。</p>`;
            });
    }

    // 定期获取合并状态，每秒更新一次
    setInterval(fetchMergeStatus, 1000);



    // 关闭浮窗
    closeBtn.addEventListener('click', () => {
        editSpeakerModal.style.display = 'none';
    });


    helpBtn.addEventListener('click', () => {
        // 显示弹窗前加载内容
        fetch('/help-content')
            .then(response => response.json())
            .then(data => {
                helpText.innerHTML = data.help_content;
                helpModal.style.display = 'block';
            })
            .catch(error => {
                helpText.innerHTML = "<p>无法加载帮助文档，请稍后再试。</p>";
                helpModal.style.display = 'block';
            });
    });

    closeHelpBtn.addEventListener('click', () => {
        helpModal.style.display = 'none';
    });

    // 当用户点击弹窗外部区域时，关闭弹窗
    window.addEventListener('click', (event) => {
        if (event.target == helpModal) {
            helpModal.style.display = 'none';
        }
    });











    // 添加新讲述人
    addSpeakerBtn.addEventListener('click', async () => {
        const newSpeakerName = newSpeakerNameInput.value.trim();
        if (newSpeakerName) {
            const response = await fetch('/add_speaker', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ speaker_name: newSpeakerName })
            });

            if (response.ok) {
                console.log('New speaker added successfully');
                loadSpeakers();  // 更新讲述人下拉菜单
                editSpeakerModal.style.display = 'none';  // 添加完成后隐藏浮窗
            } else {
                console.error('Failed to add new speaker');
            }
        }
    });

    // 点击窗体外部区域时关闭浮窗
    window.addEventListener('click', (event) => {
        if (event.target == editSpeakerModal) {
            editSpeakerModal.style.display = 'none';
        }
    });

    // 显示高级设置浮窗
    advancedSettingsBtn.addEventListener('click', () => {
        advancedSettingsModal.style.display = 'block';
        loadCustomSettings();
    });

    // 关闭高级设置浮窗
    closeSettingsBtn.addEventListener('click', () => {
        advancedSettingsModal.style.display = 'none';
    });

    // 恢复默认设置
    restoreDefaultsBtn.addEventListener('click', async () => {
        const response = await fetch('/restore_defaults', { method: 'POST' });
        if (response.ok) {
            loadCustomSettings();
            console.log('Settings restored to default');
        } else {
            console.error('Failed to restore defaults');
        }
    });

    // 加载自定义设置
    const loadCustomSettings = () => {
        fetch('/get_custom_settings')
            .then(response => response.json())
            .then(data => {
                customSettingsInput.value = data.settings || "";
            });
    };
	
// “更改”按钮点击事件
    updateSettingBtn.addEventListener('click', function() {
        const newSetting = document.getElementById('custom-setting').value;

        fetch('/update_setting', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ new_setting: newSetting })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === "success") {
                alert("设置已更新！");
                advancedSettingsModal.style.display = 'none';
            } else {
                alert("更新失败: " + data.message);
            }
        })
        .catch(error => {
            console.error('Error updating setting:', error);
            alert("更新过程中出现错误，请稍后再试。");
        });
    });

    // 保存自定义设置
    customSettingsInput.addEventListener('blur', async () => {
        const customSettings = customSettingsInput.value.trim();
        const response = await fetch('/update_custom_settings', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ custom_settings: customSettings })
        });
        if (response.ok) {
            console.log('Custom settings updated successfully');
        } else {
            console.error('Failed to update custom settings');
        }
    });
	
   helpBtn.addEventListener('click', () => {
        helpModal.style.display = 'block';
    });

    closeHelpBtn.addEventListener('click', () => {
        helpModal.style.display = 'none';
    });

    // 当用户点击弹窗外部区域时，关闭弹窗
    window.addEventListener('click', (event) => {
        if (event.target == helpModal) {
            helpModal.style.display = 'none';
        }
    });


    // 函数：加载讲述人列表并更新下拉菜单
    function loadSpeakers() {
        fetch('/get_speakers')
            .then(response => response.json())
            .then(data => {
                // 清空现有选项
                speakerDropdown.innerHTML = '';
                const speakerList = document.getElementById('speaker-list');
                speakerList.innerHTML = ''; // 清空现有列表

                if (data.speakers) {
                    data.speakers.forEach(speaker => {
                        const option = document.createElement('option');
                        option.value = speaker.name.replace('（*默认讲述者*）', '').trim(); // 确保 value 是纯粹的讲述人名称
                        option.text = speaker.name;
                        if (speaker.is_default) {
                            option.selected = true; // 设置默认讲述人为选中状态
                        }
                        speakerDropdown.appendChild(option);

                        // 创建讲述人列表项
                        const speakerItem = document.createElement('div');
                        speakerItem.className = 'speaker-item';
                        speakerItem.innerHTML = `
                            <span>${speaker.name}</span>
                            <button class="delete-speaker-btn ${speaker.is_default ? 'disabled' : ''}" data-speaker="${speaker.name}">
                                &#x2212;
                            </button>
                        `;
                        speakerList.appendChild(speakerItem);
                    });

                    // 监听删除按钮点击事件
                    document.querySelectorAll('.delete-speaker-btn').forEach(button => {
                        button.addEventListener('click', async (event) => {
                            if (button.classList.contains('disabled')) return;

                            const speakerName = event.target.getAttribute('data-speaker');
                            const response = await fetch('/delete_speaker', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ speaker_name: speakerName })
                            });

                            if (response.ok) {
                                console.log(`Speaker ${speakerName} deleted successfully`);
                                loadSpeakers(); // 重新加载讲述人列表
                            } else {
                                console.error(`Failed to delete speaker ${speakerName}`);
                            }
                        });
                    });
                }
            })
            .catch(error => console.error('Error fetching speakers:', error));
    }

    // 初始加载讲述人列表
    loadSpeakers();

    // 监听下拉菜单的变化事件
    speakerDropdown.addEventListener('change', async () => {
        const selectedSpeaker = speakerDropdown.value.replace('（*默认讲述者*）', '').trim();
        const response = await fetch('/update_default_speaker', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ speaker: selectedSpeaker })
        });
        if (response.ok) {
            console.log('Default speaker updated successfully');
            loadSpeakers(); // 重新加载讲述人列表以更新默认状态
        } else {
            console.error('Failed to update default speaker');
        }
    });

    // 页面加载时检查是否存在跳跃层和未完成的句子
    fetch('/check_gaps')
        .then(response => response.json())
        .then(data => {
            if (data.gaps_found) {
                fixGapsBtn.style.display = 'inline-block';
            }
        });

    fetch('/get_unfinished_sentence')
        .then(response => response.json())
        .then(data => {
            if (data.sentence) {
                unfinishedDiv.innerHTML = `上次中断于：${data.sentence}`;
                unfinishedDiv.style.display = 'block';
            } else {
                unfinishedDiv.style.display = 'none';
            }
        });

    // 监听 filename 输入框的失去焦点事件，独立处理 filename 的更新
    filenameInput.addEventListener('blur', async () => {
        const filename = filenameInput.value.trim();
        if (filename !== "") {
            const response = await fetch('/update_filename', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ filename: filename })
            });
            if (response.ok) {
                console.log('Filename updated successfully');
            } else {
                console.error('Failed to update filename');
            }
        }
    });

 // 页面加载时自动获取并显示 filename
fetch('/get_filename')
    .then(response => response.json())
    .then(data => {
        if (data.filename) {
            filenameInput.value = data.filename;
            toggleClearButton(); // 获取到 filename 后立即检查按钮显示状态
        }
    });

// 新增：根据 filename 字段是否有值显示或隐藏清空按钮
function toggleClearButton() {
    if (filenameInput.value.trim() !== "") {
        clearFilenameBtn.style.display = "inline-block"; // 显示按钮
    } else {
        clearFilenameBtn.style.display = "none"; // 隐藏按钮
    }
}

// 页面加载时检查 filename 字段并设置按钮显示状态
toggleClearButton();

// 在 filename 输入框内容变化时检查
filenameInput.addEventListener('input', toggleClearButton);

// 清空按钮的点击事件
//clearFilenameBtn.addEventListener('click', () => {
//    filenameInput.value = ""; // 清空输入框内容
//    toggleClearButton(); // 隐藏按钮
//});

// 监听“清空”按钮的点击事件
    clearFilenameBtn.addEventListener('click', async () => {
        filenameInput.value = "";  // 清空输入框内容
        const response = await fetch('/update_filename', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ filename: "" })
        });
        if (response.ok) {
            console.log('Filename cleared successfully');
                toggleClearButton(); // 隐藏按钮
        } else {
            console.error('Failed to clear filename');
        }
    });


    // 提交和继续按钮只负责 text 表单的提交，不再处理 filename
    form.addEventListener('submit', async (event) => {
        event.preventDefault();
        statusDiv.innerHTML = 'Processing...';
        unfinishedDiv.innerHTML = ''; // 提交后清空未完成的句子显示
        unfinishedDiv.style.display = 'none'; // 隐藏未完成的句子显示

        const formData = new FormData(form);
        formData.delete('filename'); // 确保提交时不包含 filename
        formData.append('text', document.getElementById('text').value); // 仅提交 text 字段
        const url = submitBtn.value === '继续处理' ? '/continue' : '/process_text';
        const response = await fetch(url, {
            method: 'POST',
            body: formData
        });

        if (response.ok) {
            const result = await response.json();
            statusDiv.innerHTML = `Processing started for text: ${result.text}`;
                        if (result.filename) {
                filenameInput.value = result.filename; // 更新表单中的 filename 输入框
                console.log(`Filename updated to: ${result.filename}`);
            }
            pollProgress(); // 启动轮询，更新状态栏
        } else {
            statusDiv.innerHTML = '处理失败，请重试。';
        }
    });

    // 清空并停止按钮的点击事件处理程序
    clearBtn.addEventListener('click', async () => {
        const response = await fetch('/clear_progress', { method: 'POST' });
        if (response.ok) {
            statusDiv.innerHTML = 'Progress cleared.';
            unfinishedDiv.innerHTML = ''; // 清空按钮点击后也清空未完成的句子显示
            unfinishedDiv.style.display = 'none'; // 隐藏未完成的句子显示
            submitBtn.value = '停止且清空数据';
            clearBtn.style.display = 'none';
            
            // 添加页面刷新逻辑
            location.reload();  // 原地刷新页面
        } else {
            console.error('Failed to clear progress');
        }
    });

    stopBtn.addEventListener('click', async () => {
        const response = await fetch('/stop_processing', { method: 'POST' });
        if (response.ok) {
            statusDiv.innerHTML = 'Processing stopped';
        }
    });


mergeBtn.addEventListener('click', async () => {
    try {
        // 检查当前进程状态
        const progressResponse = await fetch('/progress');
        const progressData = await progressResponse.json();

        if (progressData.status === 'processing') {
            // 如果正在处理，则先停止进程
            statusDiv.innerHTML = '正在停止当前进程...';
            const stopResponse = await fetch('/stop_processing', { method: 'POST' });
            if (!stopResponse.ok) {
                statusDiv.innerHTML = '停止进程失败，无法执行合并。';
                return;
            }
        }

        // 停止成功或无进程时，触发合并操作
        const mergeResponse = await fetch('/trigger_merge', { method: 'POST' });
        if (mergeResponse.ok) {
            statusDiv.innerHTML = '合并已触发';
            pollProgress(); // 启动轮询，更新状态栏
        } else {
            statusDiv.innerHTML = '合并触发失败，请重试。';
        }
    } catch (error) {
        console.error('Error during merge process:', error);
        statusDiv.innerHTML = '合并过程出现错误，请重试。';
    }
});


    // “修复断层”按钮事件监听器
    fixGapsBtn.addEventListener('click', async () => {
        disableButtons();

        const response = await fetch('/fix_gaps', { method: 'POST' });
        if (response.ok) {
            listenForFixProgress(); // 启动轮询，检查修复进程状态
        } else {
            statusDiv.innerHTML = '断层修复失败，请重试。';
            enableButtons(); // 如果失败，重新启用按钮
        }
    });

    const listenForFixProgress = () => {
        const intervalId = setInterval(async () => {
            try {
                const response = await fetch('/fix_progress');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const progressData = await response.json();
                updateFixProgress(progressData);

                if (progressData.processed_gaps >= progressData.total_gaps) {
                    clearInterval(intervalId);
                    alert('断层修复完成，即将刷新页面...');
                    location.reload(); // 刷新页面以重置按钮状态
                }
            } catch (error) {
                console.error('Error fetching fix progress:', error);
            }
        }, 1000);
    };

    const updateFixProgress = (progressData) => {
        const { total_gaps, processed_gaps, current_gap } = progressData;
        const remaining_gaps = total_gaps - processed_gaps;
        fixProgressDiv.style.display = 'block';
        if (total_gaps === 0) {
            fixProgressDiv.innerHTML = '没有需要修复的断层。';
            return;
        }

        fixProgressDiv.innerHTML = `合计有${total_gaps}个断层，已经处理${processed_gaps}个断层，剩余${remaining_gaps}个断层。`;

        if (current_gap) {
            fixProgressDiv.innerHTML += `<br> 正处理的断层范围：${current_gap[0]} - ${current_gap[1]}`;
        }
    };

    const disableButtons = () => {
        document.querySelectorAll('button').forEach(button => {
            if (button.id !== 'stop-btn') {
                button.disabled = true;
            }
        });
    };

    const enableButtons = () => {
        document.querySelectorAll('button').forEach(button => {
            button.disabled = false;
        });
    };

    const pollProgress = () => {
        const intervalId = setInterval(async () => {
            const progressResponse = await fetch('/progress');
            const progressData = await progressResponse.json();

            if (progressData.status === 'processing') {
                const percentage = ((progressData.current_index / progressData.total_index) * 100).toFixed(2);
                statusDiv.innerHTML = `正在处理第 ${progressData.current_index} 句 (${percentage}%)：${progressData.sentence}`;
                updateProgressBar(progressData.current_index, progressData.total_index);
                updateDetailedInfo(progressData);
            } else if (progressData.status === 'complete') {
                statusDiv.innerHTML = `处理完成。合并文件: ${progressData.merged_filename}`;
                clearInterval(intervalId);
            } else if (progressData.status === 'timeout') {
                statusDiv.innerHTML = '处理超时。';
                clearInterval(intervalId);
                submitBtn.value = '继续处理';
            } else {
                statusDiv.innerHTML = '处理失败，请重试。';
                clearInterval(intervalId);
            }
        }, 1000);
    };

    const updateProgressBar = (currentIndex, total) => {
        const percentage = (currentIndex / total) * 100;
        progressBar.style.width = `${percentage}%`;
    };

    fetch('/progress')
        .then(response => response.json())
        .then(progressData => {
            updateDetailedInfo(progressData);
        });

    const fetchDetailedInfo = () => {
        fetch('/get_detailed_info')
            .then(response => response.json())
            .then(data => {
                if (data.errors && data.errors.length > 0) {
                    detailedInfoDiv.innerHTML = data.errors.map(error => `<p>${error.timestamp}: ${error.message}</p>`).join('');
                }
            });
    };

    const updateDetailedInfo = (progressData) => {
        const { book_title, chapter_count, section_count, total_sentences, total_duration, current_index, total_index } = progressData;
        if (book_title) {
            detailedInfoDiv.innerHTML = `
                <p>当前对本文捕获了疑似书名，为：《${book_title}》。如果需要订正，需要你在可选文件名处输入指定文件名并点击提交/继续。</p>
                <p>当前已经为你拆分 ${chapter_count || 0} 章 ${section_count || 0} 节，合计 ${total_sentences || 0} 句。</p>
                <p>累计已接收 ${Math.floor(total_duration / 3600)} 时 ${Math.floor((total_duration % 3600) / 60)} 分 ${Math.floor(total_duration % 60)} 秒的音频文件。</p>
            `;
        } else {
            detailedInfoDiv.innerHTML = `
                <p>本文程序抓不到书名或文章，你可手动输入。</p>
                <p>当前已经为你拆分 ${chapter_count || 0} 章 ${section_count || 0} 节，合计 ${total_sentences || 0} 句。</p>
                <p>累计已接收 ${Math.floor(total_duration / 3600)} 时 ${Math.floor((total_duration % 3600) / 60)} 分 ${Math.floor(total_duration % 60)} 秒的音频文件。</p>
            `;
        }

        if (progressData.progress_summary) {
            unfinishedDiv.innerHTML = progressData.progress_summary;
            unfinishedDiv.style.display = 'block';
        } else {
            unfinishedDiv.style.display = 'none';
        }
    };

    // 初始加载详细错误信息
    fetchDetailedInfo();
});
